package com.miku.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class SolrUtil {
	private String solrDomain;
	private static Logger logger = LoggerFactory.getLogger(Net.class);
	
	public void initialize(){
		fullImport();
	}
	
	public void destroy(){
		
	}
	
	public static String replaceSpecialChar(String key){
		if(key == null) return null;
		key = key.replaceAll("\\^", " ");
		key = key.replaceAll("\\~", " ");
		key = key.replaceAll("\\*", " ");
		key = key.replaceAll("\\?", " ");
		key = key.replaceAll(":", " ");
		key = key.replaceAll("\\+", " ");
		key = key.replaceAll("-", "");
		key = key.replaceAll("&", " ");
		key = key.replaceAll("|", " ");
		key = key.replaceAll("!", " ");
		key = key.replaceAll("\\(", " ");
		key = key.replaceAll("\\)", " ");
		key = key.replaceAll("\\{", " ");
		key = key.replaceAll("\\}", " ");
		key = key.replaceAll("\\[", " ");
		key = key.replaceAll("\\]", " ");
		key = key.replaceAll("\"", " ");
		key = key.replaceAll("\\\\", " ");
		return key;
	}
	
	public void fullImport(){
		//全部导入，清空原数据
		//http://localhost:8081/solr/dataimport?command=full-import
		logger.debug("restruct solr: " + solrDomain);
		//String ret = query("dataimport?command=full-import&wt=json", "cannot restruct solr.");
		//logger.debug(ret);
		logger.debug("restruct solr----------------------------------------ok");
	}
	
	private String query(String action, String err){
		String ret = Net.queryStringGet(solrDomain + action);
		if(ret == null && err != null) throw new RuntimeException(err);
		return ret;
	}
	
	/**
	 * 使用solr进行搜索，全文检索
	 * @param keyword 查询的关键字
	 * @param fl              返回的字段名，如果为null，将返回所有字段
	 * @param sort          排序的字段名
	 * @param start         开始行
	 * @param rows        结果的行数
	 * @return  返回solr的结果response
	 */
	public JSONObject search(String keyword, String fl, String sort, Integer start, Integer rows){
		//http://localhost:8983/solr/hufu/select?q=%E5%A5%B3%E7%8E%8B&wt=json&indent=true
		String ret = query("select?q=" + Encodes.urlEncode(keyword) + 
				"&wt=json" + 
				(fl != null ? "&fl="+ fl : "") + 
				(sort != null ? "&sort="+ sort : "") + 
				(start != null ? "&start="+ start : "") +
				(rows != null ? "&rows="+ rows : "")
				, "cannot query search.");
		if(ret == null) return null;
		JSONObject j = JSON.parseObject(ret);
		JSONObject response = j.getJSONObject("response");
		return response;
	}

	public String getSolrDomain() {
		return solrDomain;
	}

	public void setSolrDomain(String solrDomain) {
		if(solrDomain != null && !solrDomain.endsWith("/")) solrDomain += "/";
		this.solrDomain = solrDomain;
	}
}
